# -*- coding: utf-8 -*-

'''
/**
 * @addtogroup hj1239_tcp_server
 * hj1239_tcp_server
 * @{
 */
/**
 * @file        hj1239_tcp_server.py
 * @brief       XXXX
 * @note        XXXX
 * @author      靳普诏(puzhao.jin@hopechart.com)
 * @date        2023/09/23
 * @version     1.0

 * @par         修改日志
 * <table>
 * <tr><th>Date         <th>Version     <th>Author      <th> Description
 * <tr><td>2023/09/23   <td>1.0         <td>靳普诏       <td> 创建初始版本
 * @copyright   xxxx
 */
'''

import sys
import os
from msg_hj1239 import *
from msg_hj1239_cmd_0x01 import *
from msg_hj1239_cmd_0x02 import *
from msg_hj1239_cmd_0x03 import *
from msg_hj1239_cmd_0x04 import *
from msg_hj1239_cmd_0x05 import *
from msg_hj1239_cmd_0x06 import *
from msg_hj1239_cmd_0x07 import *
from msg_hj1239_cmd_0x08 import *

## 获取当前脚本所在的目录
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))

sys.path.insert(0, f"{SCRIPT_DIR}/../")
from az_tcp_server import *
from datetime import datetime

def CmdUnitLabel(cmd: int):
    result = "系统预留"
    if cmd == 0x01:
        result = "车辆登入"
    elif cmd == 0x02:
        result = "实时信息上报"
    elif cmd == 0x03:
        result = "补发信息上报"
    elif cmd == 0x04:
        result = "车辆登出"
    elif cmd == 0x05:
        result = "终端校时"
    elif cmd == 0x06:
        result = "车辆拆除报警信息"
    elif cmd == 0x07:
        result = "激活信息"
    elif cmd == 0x08:
        result = "激活信息应答"
    elif cmd == 0xC1:
        result = "天行健平台扩展命令数据"
    elif cmd == 0xC3:
        result = "压缩数据"
    return result

def Bytes2HexStr(data: bytes, col_cnt = 32, with_blank = True):
    ret = ''
    pos = 0
    blank = " " if with_blank else ""

    for i in data:
        if (i < 0x10):
            ret += f"0{hex(i)[2:]}{blank}"
        else:
            ret += f"{hex(i)[2:]}{blank}"
        
        if col_cnt > 0:
            pos += 1
            if pos == col_cnt:
                ret += '\n'
                pos = 0

    return ret

def GenCurrTimeStr():
    now = datetime.now()
    return now.strftime("%H:%M:%S")

def GenLogFilename(topdir, addr:str):
    now = datetime.now()

    date = now.strftime("%Y-%m-%d")
    fdir = f"{topdir}/{date}"
    if not os.path.exists(fdir):
            os.makedirs(fdir)

    time = now.strftime("%H·%M·%S")
    addr.replace(' ','')
    ret = f"{fdir}/{time}_{addr}.txt"
    return ret


class THj1239TcpServer(TAzTcpServerBase):
    def __init__(self, host="127.0.0.1", port=60006, listen_cnt=1, connect_timeout_sec=1800):
        super().__init__(host, port, listen_cnt, connect_timeout_sec)
        self.log_dir = f"{SCRIPT_DIR}/log_dir"
        self.file_handle = {}
        return
    
    def __Log(self, addr: str, log:str, end = '\n'):
        f_handle = self.file_handle[addr]
        print(log, end = end)
        f_handle.write(log + end)

    def Start(self, join_timeout=None):
        # if not os.path.exists(self.log_dir):
        #     os.makedirs(self.log_dir)
        return super().Start(join_timeout)

    def OnConnect(self, client_socket: socket.socket, addr: str):
        log = f"[{GenCurrTimeStr()} OnConnect] --- client_socket_addr:{addr}"
        log_filename = GenLogFilename(self.log_dir, addr.__str__())
        f_handle = open(log_filename, 'w+', encoding='utf-8')
        self.file_handle[addr] = f_handle
        self.__Log(addr, log)

    def OnDisconnect(self, addr: str, disconnect_type: TAzSocketDisconnectType, log: str):
        log = f"\n[{GenCurrTimeStr()} OnDisconnect] -/- client_socket_addr:{addr}, type:{log}, type_id:{disconnect_type.name}"
        f_handle = self.file_handle[addr]
        self.__Log(addr, log)
        f_handle.close()
        self.file_handle.pop(addr)
        
    def OnSend(self, client_socket: socket.socket, addr: str, send_data: bytes, send_result):
        log = f"\n[{GenCurrTimeStr()} OnSend] >>> client_socket_addr:{addr}, send_result:{send_result}, data:\n{Bytes2HexStr(send_data)}"
        self.__Log(addr, log)
        
    def OnRecv(self, client_socket: socket.socket, addr: str, recv_data: bytes):
        log = f"\n[{GenCurrTimeStr()} OnRecv] <<< client_socket_addr:{addr}, recv_size:{recv_data.__len__()}, data:\n{Bytes2HexStr(recv_data)}"
        self.__Log(addr, log)
        # self.Send(addr, recv_data)
        self.__MessageParser(client_socket, addr, recv_data)
        self.file_handle[addr].flush()


    def __MessageParser(self, client_socket: socket.socket, addr: str, recv_data: bytes):
        msg = TMsgHj1239()

        if not msg.Decode(recv_data):
            self.__Log(addr, "数据包格式错误!!!")
            return
        
        cmd_unit = msg.GetCmdUnit()
        self.__Log(addr, f"命令单元：{hex(cmd_unit)}, {CmdUnitLabel(cmd_unit)}")
        self.__Log(addr, f"车辆识别号：{msg.GetVin()}")
        self.__Log(addr, f"终端软件版本号：{msg.GetTermVersion()}")
        self.__Log(addr, f"数据加密方式：{msg.GetEncryptionType()}")
        data_unit_len = msg.GetDataUnitLen()
        self.__Log(addr, f"数据单元长度：{data_unit_len}")
        if data_unit_len > 0:
            self.__Log(addr, f"数据单元：{Bytes2HexStr(msg.GetDataUnit(), col_cnt = 0, with_blank = False)}")
        
        self.__CmdMsgParser(cmd_unit, client_socket, addr, msg.GetDataUnit())
        return

    def __CmdMsgParser(self, cmd: int, client_socket: socket.socket, addr: str, recv_data: bytes):
        f_handle = self.file_handle[addr]
        msg = None
        if cmd == 0x01:
            result = "车辆登入"
            msg = TMsgHJ1239Cmd01(f_handle)
        elif cmd == 0x02:
            result = "实时信息上报"
            msg = TMsgHJ1239Cmd02(f_handle)
        elif cmd == 0x03:
            result = "补发信息上报"
        elif cmd == 0x04:
            result = "车辆登出"
        elif cmd == 0x05:
            result = "终端校时"
        elif cmd == 0x06:
            result = "车辆拆除报警信息"
        elif cmd == 0x07:
            result = "激活信息"
        elif cmd == 0x08:
            result = "激活信息应答"
        elif cmd == 0xC1:
            result = "天行健平台扩展命令数据"
        elif cmd == 0xC3:
            result = "压缩数据" 
        
        if msg != None and msg.Decode(recv_data):
            msg.MessageParser(client_socket, addr, recv_data)

        return

if __name__ == "__main__":
    
    # 输出目录路径
    print("SCRIPT_DIR: "+ SCRIPT_DIR)

    ## 获取脚本传参
    argv = sys.argv
    argc = len(argv)
    # 打印命令行参数
    #for i in range(1, argc):
        #print("参数", i, ":", argv[i])
        
    print("============= BIGEN: hj1239_tcp_server.py =============")

    server = THj1239TcpServer("127.0.0.1", 9999)
    server.recv_buff_size = 2048
    server.Start()
    a = b'\x11\x02'
    str = hex(a[1])
    print(str)

    print("============= END: hj1239_tcp_server.py =============")



## Generated on "2023-09-23 18:33:26" by the tool "gen_hq_file.py >> V20230509_1" 